#include<iostream>
using namespace std;
#include"Thread.hpp"
#include<memory>
#include<pthread.h>
#include"Mutex.hpp"
#include<unistd.h>

// void* thread_run(void* args){
//     string name = static_cast<const char*>(args);
//     while(true){
//         cout<<"我是新线程，我正在做:"<<name<<endl;
//         sleep(1);
//     }
    
// }

class ThreadData{
public:
    ThreadData(const string& name,pthread_mutex_t* mutex):_name(name),_mutex_t(mutex){

    }
    ~ThreadData(){

    }

public:
    string _name;//线程的名称
    pthread_mutex_t* _mutex_t;//锁
};



int ticket = 10000;
void* get_ticket(void* args){
    ThreadData* td = static_cast<ThreadData*>(args);

    //加锁
    while(true){
        lockguard grand(td->_mutex_t);//raii
       // pthread_mutex_lock(td->_mutex_t);
        //pthread_mutex_lock(td->_mutex_t);
        if(ticket > 0){
            //抢票
           // usleep(124);
            cout<<td->_name<<"正在抢票："<<ticket<<endl;
            ticket--;
           // pthread_mutex_unlock(td->_mutex_t);
        }else{
            //pthread_mutex_unlock(td->_mutex_t);
            break;
        }
    }
    return nullptr;
}



#define NUM 4;
//线程同步和互斥的测试
int main(){
    //在主线程定义锁
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);

    vector<pthread_t> tids(4);

    for(int i = 0;i<4;i++){
        char buffer[128];
        snprintf(buffer,sizeof buffer,"thread : %d",i+1);
        ThreadData* td = new ThreadData(buffer,&lock);
        pthread_create(&tids[i],nullptr,get_ticket,td);
    
    }

    //等待进程
    for(auto e: tids){
        pthread_join(e,nullptr);
    }




    // pthread_t t1,t2,t3,t4;
    // pthread_create(&t1,nullptr,get_ticket,(void*)"thread 1");
    // pthread_create(&t2,nullptr,get_ticket,(void*)"thread 2");
    // pthread_create(&t3,nullptr,get_ticket,(void*)"thread 3");
    // pthread_create(&t4,nullptr,get_ticket,(void*)"thread 4");


    // pthread_join(t1,nullptr);
    // pthread_join(t2,nullptr);
    // pthread_join(t3,nullptr);
    // pthread_join(t4,nullptr);





    pthread_mutex_destroy(&lock);






//    unique_ptr<Thread> t1(new Thread(thread_run,(void*)"hello1",1));
//    unique_ptr<Thread> t2(new Thread(thread_run,(void*)"hello2",2));
//    unique_ptr<Thread> t3(new Thread(thread_run,(void*)"hello3",3));
//    unique_ptr<Thread> t4(new Thread(thread_run,(void*)"hello4",4));

//    t1->join();
//    t2->join();
//    t3->join();
//    t4->join();



    




    return 0;
}